<?php

declare( strict_types = 1 );
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Common as com;
use App\Controller as nameController;
use App\Common\Server\Api as nameApi;
use Psr\Http\Message\ResponseInterface;

class Api extends nameController\Base {

	/**
	 * @return ResponseInterface
	 */
	public function index():ResponseInterface {
/*		d('a');
		return $this->response->json( [
			'ok'
		] );*/
		try{
			// 初始化mock数据
			// $this->initMockData();
			// 初始化网关
			$apiGateway = com\Server\Api\Gateway::newClassOfWebApi( $this->request );
			// 设置参数
			// $apiGateway->apiRouter()->apiRequest()->apiData()->setApiPrefix( $this->getApiPrefix() );
			// 处理
			$apiResponse = $apiGateway->handle();
		} catch( \Throwable $e ){
			// 处理异常
			$apiResponse = nameApi\Exception::new( $e )->toApiResponse();
		}
		// 返回Response信息
		return $this->response->json( $apiResponse->getApiResponse()->toArray() );
	}

	/**
	 * 初始化mock数据
	 */
	private function initMockData() {
		// 修改为POST请求
		com\Lib\Hyperf\Request::withMethod( 'post' );
		// 修改post参数
		$postParam = $this->request->all();
		// $postParam['api'] = $postParam['api'] ?? 'user.login.ofWeixin';
		// $postParam['api'] = $postParam['api'] ?? 'sys.token.apply';
		if( ! isset( $postParam['api'] ) ){
			$postParam['api'] = 'sys.token.apply';
		}
		com\Lib\Hyperf\Request::withQueryParams( $postParam );
	}

	/**
	 * 获取api前缀
	 * @return string
	 */
	private function getApiPrefix() {
		$apiPrefix = substr( $this->request->getPathInfo(), 4 );
		$apiPrefix = str_replace( '/', '.', $apiPrefix );
		$apiPrefix = str_replace( '-', '_', $apiPrefix );
		$apiPrefix = com\Lib\Fun\Str::parseName( $apiPrefix, 1, false );
		$apiPrefix = ltrim( $apiPrefix, '.' );
		//
		if( $apiPrefix !== '' ){
			$apiPrefix .= '.';
		}
		//
		return $apiPrefix;
	}

}
